package com.myhkvideo.yulongbpcdemo.Scheduler;

import com.myhkvideo.yulongbpcdemo.entity.MetalAndGradeAndRateDayInfoData;
import com.myhkvideo.yulongbpcdemo.mapper.MetalAndGradeAndRateDayInfoMapper;
import com.myhkvideo.yulongbpcdemo.service.MetalAndGradeAndRateDayInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
@Component
public class MetalAndGradeAndRateDayInfoScheduler {

    @Autowired
    private MetalAndGradeAndRateDayInfoService metalAndGradeAndRateDayInfoService;

    @Autowired
    private MetalAndGradeAndRateDayInfoMapper metalAndGradeAndRateDayInfoMapper;

    String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    /**
     * 将 MetalAndGradeAndRateDayInfoData 数据插入数据库
     */
    @Scheduled(fixedRate = 60 * 60 * 1000) // 5分钟执行一次
    public void insertMetalAndGradeAndRateDayInfoData() {
        try {
            List<MetalAndGradeAndRateDayInfoData> dataList = metalAndGradeAndRateDayInfoService.getAndConvertMetalAndGradeAndRateDayInfo();
            for (MetalAndGradeAndRateDayInfoData data : dataList) {
                if (metalAndGradeAndRateDayInfoMapper.checkDataExists(data.getCreateTime()) > 0) {
                    // 数据存在，更新数据
                    metalAndGradeAndRateDayInfoMapper.updateData(data);
                } else {
                    // 数据不存在，插入新数据
                    data.setId(UUID.randomUUID().toString());
                    metalAndGradeAndRateDayInfoMapper.insertData(data);
                }

            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        System.out.println(currentDateTime+"全矿日金属量、精矿品位、精矿回收率数据更新成功");
    }
}
